package br.com.livro.javapersistence.commons.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;

import br.com.guj.hibernate.model.Arquivo;
import br.com.guj.hibernate.model.Extensao;
import br.com.livro.javapersistence.commons.persistence.NammingStrategy;

/**
 * @author leo
 * 
 */
public class HibernateUtil {

	private static SessionFactory sessionFactoryXml;
	private static SessionFactory sessionFactoryAnnotation;

	/**
	 * @return
	 */
	public static SessionFactory getSessionFactoryXml(boolean isCriacao) {
		if (sessionFactoryXml == null) {
			HibernateUtil.initializeSessionFactoryXml(isCriacao);
		}
		return sessionFactoryXml;
	}

	/**
	 * @param isCriacao
	 * @param annotatedClasses
	 * @return 
	 */
	public static SessionFactory getSessionFactoryAnnotation(boolean isCriacao, ExecucaoHibernate execucaoHibernate) {
		if (sessionFactoryAnnotation == null)
			HibernateUtil.initializeSessionFactoryAnnotation(isCriacao, execucaoHibernate);

		return sessionFactoryAnnotation;
	}

	/**
	 * @param isCriacao
	 */
	private static void initializeSessionFactoryXml(boolean isCriacao) {
		Configuration xmlConfiguration = new Configuration();
		xmlConfiguration.setNamingStrategy(new NammingStrategy());
		xmlConfiguration.configure(HibernateUtil.getResourceConfiguration());
		xmlConfiguration.addResource("br/com/livro/javapersistence/commons/model/Enum.hbm.xml");
		xmlConfiguration.addResource("br/com/livro/javapersistence/commons/model/Enum.hbm.xml");
		xmlConfiguration.addResource("br/com/livro/javapersistence/others/model/HistoryMapa.hbm.xml");
		xmlConfiguration.setProperty(Environment.HBM2DDL_AUTO, isCriacao ? "create" : "update");
		sessionFactoryXml = xmlConfiguration.buildSessionFactory();
	}

	/**
	 * @param isCriacao
	 * @param annotatedClasses
	 */
	private static void initializeSessionFactoryAnnotation(boolean isCriacao, ExecucaoHibernate execucaoHibernate) {
		AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
		annotationConfiguration.configure(HibernateUtil.getResourceConfiguration());
		annotationConfiguration.setProperty(Environment.HBM2DDL_AUTO, isCriacao ? "create" : "update");
		annotationConfiguration.setNamingStrategy(new NammingStrategy());
		// TODO mudar para enum
		{
			execucaoHibernate.addAnnotatedClass(annotationConfiguration);
//			annotationConfiguration.addAnnotatedClass(Arquivo.class);
//			annotationConfiguration.addAnnotatedClass(Extensao.class);
		}

		sessionFactoryAnnotation = annotationConfiguration.buildSessionFactory();

	}

	public static String getResourceConfiguration() {
		return "br/com/livro/javapersistence/commons/hibernate.cfg.xml";
	}
}
